<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\kuaishou;

use app\command\BaseWork;
use app\enum\BatchProjectEnum;
use app\enum\ConfigEnum;
use app\enum\KuaiShouEnum;
use app\model\BatchProjectContentModel;
use app\service\batch\kuaishou\CreateProjectService;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;

class BatchUnitPushWork extends BaseWork
{
    public const REDIS_TASK_KEY = ConfigEnum::CACHE_CONFIG[KuaiShouEnum::BATCH_CONFIG_KEY]['batch_unit'];

    protected function configure()
    {
        // 指令配置
        $this->setName('ks_batch_unit_push_work');
        // 设置参数
        $this->setDescription('快手智能化搭建组推送');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->getOutputMessage('快手智能化搭建组开始');
        $redis = Cache::store('redis')->handler();
        $st = time() + 5 * 60;
        while (time() < $st) {
            $id = $redis->lPop(self::REDIS_TASK_KEY);
            if (! $id) {
                sleep(rand(5, 10));
                continue;
            }
            $this->getOutputMessage('快手智能化搭建组[' . $id . ']开始');
            $model = (new BatchProjectContentModel())->where('id', $id)->find();
            if (! $model instanceof BatchProjectContentModel || ! $model->getKey()) {
                $this->getOutputMessage('快手智能化搭建组[' . $id . ']失败：结构体不存在');
                continue;
            }
            // 判断状态
            if ($model->getAttr('status') == BatchProjectEnum::STATUS_SUCCESS) {
                continue;
            }
            try {
                if (! CreateProjectService::projectUnitCreate($model)) {
                    CreateProjectService::setFalse($model, CreateProjectService::getError(0));
                    $this->getOutputMessage('快手智能化搭建组[' . $id . ']失败：' . CreateProjectService::getError(0));
                }
                $this->getOutputMessage('快手智能化搭建组[' . $id . ']结束');
            } catch (\Exception $e) {
                CreateProjectService::setFalse($model, $e->getMessage());
                $this->getOutputMessage($e->getMessage());
                $this->getOutputMessage($e->getFile() . '[' . $e->getLine() . ']');
                $this->getOutputMessage($e->getTraceAsString());
            }
        }
        $this->getOutputMessage('快手智能化搭建组结束');
    }
}
